@echo off
chcp 65001 >nul 2>&1

:: ==============================================
:: MODIFY THIS (REQUIRED)
:: ==============================================
set "COMMIT_MESSAGE=update android res: layout, drawable and mipmap files"

:: ==============================================
:: 1. Check if in Git repository
:: ==============================================
echo Step 1/5: Checking Git repository...
set "repo_root="
for /f "delims=" %%d in ('git rev-parse --show-toplevel 2^>nul') do set "repo_root=%%d"
if not defined repo_root (
    echo Error: Not a Git repository!
    pause
    exit /b 1
)
cd /d "%repo_root%"

:: ==============================================
:: 2. Handle unfinished merge (if exists)
:: ==============================================
echo Step 2/5: Handling unfinished merge...
if exist ".git/MERGE_HEAD" (
    echo Found unfinished merge, committing...
    git commit -m "Complete previous merge: %COMMIT_MESSAGE%" >nul 2>&1
    if %errorlevel% equ 0 (
        echo Merge completed.
    ) else (
        echo Error: Failed to complete merge. Resolve manually.
        pause
        exit /b 1
    )
) else (
    echo No unfinished merge.
)

:: ==============================================
:: 3. Commit local changes
:: ==============================================
echo Step 3/5: Committing local changes...
git add .
git commit -m "%COMMIT_MESSAGE%"
if %errorlevel% neq 0 (
    echo Info: No new changes to commit.
)

:: ==============================================
:: 4. Pull remote master
:: ==============================================
echo Step 4/5: Pulling remote master...
git pull origin master
if %errorlevel% neq 0 (
    echo Error: Pull failed. Resolve conflicts manually first.
    pause
    exit /b 1
)

:: ==============================================
:: 5. Push current branch
:: ==============================================
echo Step 5/5: Pushing current branch...
git push
if %errorlevel% neq 0 (
    echo Info: First push, setting upstream...
    git push -u origin HEAD
    if %errorlevel% neq 0 (
        echo Error: Push failed. Check network or permissions.
        pause
        exit /b 1
    )
)

echo ==============================================
echo Success! All operations completed.
echo ==============================================
pause